<template>
  <!-- 列表曲线组件 -->
  <div class="box">
    <el-drawer v-model="open_chart" custom-class="detail" close-on-click-modal :modal="true" @close="closeChart">
        <template #header>
          <div class="d_header">
            <div class="title">
              <svg-icon icon-class="biaotitubiao"/>
              <div style="margin: 0 0 0 8px">
                曲线详情
              </div>
            </div>
          </div>
        </template>
        <template #default>
          <div class="detail_box">
            <div id="chart"></div>
          </div>
        </template>
        <template #footer>
          <div class="footer_btns">
            <div>
              <el-button @click="closeChart">取消</el-button>
            </div>
          </div>
        </template>
      </el-drawer>
  </div>
</template>

<script setup>
import { ref,computed, nextTick, onMounted, reactive,watch } from "vue";
import * as echarts from "echarts";
import dayjs from "dayjs";
import imgIcon from "@/assets/images/youbiao.png";
import axios from "@/utils/request";

let chart = ref(null);
let chartCon
const props = defineProps({
  data: {
    type: Object,
    default: () => ({}),
  },
  openChart: {
    type: Boolean,
    default: false,
  },
  attrObj: {
    type: Object,
    default: () => {
      return undefined;
    },
  },
});
const emits = defineEmits(["closeChart"]);
const open_chart = computed(() => props.openChart);
const chartList = ref([]);
const alarmList = ref([]);
const state = reactive({
  chartShow: true,
  xydata: {
    x: 0,
    y: 0,
  },
  symShow: false,
  symbolObj: {},
  symbolShow: false,
  splitNumber: 10,
  youXY: {
    x: 0,
    y: 0,
  },
  youBoxShow: false,
  youBoxList: [],
  chartValueType: undefined,
});

// 获取曲线数据
const getChartData = async () => {
  const res = await axios.post('/pointData/simulateLine',props.data);
  if(res.code == 200){
    chartList.value = res.data;
    getDottedData();
  }
};

// 获取虚线报警数据
const getDottedData = async () => {
  const res = await axios.post('/pointData/hisAlarmLine',props.data);
  if(res.code == 200){
    alarmList.value = res.data;
    console.log(chartCon);
    
    setChart(chartList.value,alarmList.value);
  }
};

// 设置曲线图表
const setChart = (arr, alarmList) => {
  let xdata = [];
  let serArr = [];
  let xdataalarm = [];
  let serArralarm = [];
  if (JSON.stringify(arr) != "{}") {
    xdata = arr.allTimes.map((item) => {
      return dayjs(item).format("YYYY-MM-DD HH:mm:ss");
    });
    arr.hisSimulateLines.forEach((item, index) => {
      serArr.push(
        {
          name: item.pointId + item.place,
          type: "line",
          smooth: false,
          symbolSize: 8,
          xAxisIndex: 0,
          symbol:
            props.symbolShow ||
            (item.attrObj && item.attrObj.maxdotSwitch) ||
            (props.attrObj && props.attrObj.chartDot)
              ? "circle"
              : "none", //"circle",
          itemStyle: {
            normal: {
              color:
                item.color == null
                  ? item.attrObj && item.attrObj.maxlineColor
                  : item.color,
            },
          },
          lineStyle: {
            width:
              item.attrObj && item.attrObj.maxlineWidth
                ? item.attrObj.maxlineWidth
                : 2,
            opacity: item.opacity,
          },
          data: item.hisSimulatePoints.map((itemsub) => {
            return [
              dayjs(itemsub.dataTime).format("YYYY-MM-DD HH:mm:ss"),
              itemsub.maxValue,
            ];
          }),
        },
        {
          name: item.pointId + item.place,
          type: "line",
          smooth: false,
          symbolSize: 8,
          xAxisIndex: 0,
          symbol:
            props.symbolShow ||
            (item.attrObj && item.attrObj.mindotSwitch) ||
            (props.attrObj && props.attrObj.chartDot)
              ? "circle"
              : "none", //"circle",
          // symbol: props.symbolShow?props.symbolShow:item.attrObj&&item.attrObj.mindotSwitch, //"circle",
          itemStyle: {
            normal: {
              color:
                item.color == null
                  ? item.attrObj && item.attrObj.minlineColor
                  : item.color,
            },
          },
          lineStyle: {
            width:
              item.attrObj && item.attrObj.minlineWidth
                ? item.attrObj.minlineWidth
                : 2,
            opacity: item.opacity,
          },
          data: item.hisSimulatePoints.map((itemsub) => {
            return [
              dayjs(itemsub.dataTime).format("YYYY-MM-DD HH:mm:ss"),
              itemsub.minValue,
            ];
          }),
        },
        {
          name: item.pointId + item.place,
          type: "line",
          smooth: false,
          symbolSize: 8,
          xAxisIndex: 0,
          symbol:
            props.symbolShow ||
            (item.attrObj && item.attrObj.avgdotSwitch) ||
            (props.attrObj && props.attrObj.chartDot)
              ? "circle"
              : "none", //"circle",
          // symbol: props.symbolShow?props.symbolShow:item.attrObj&&item.attrObj.avgdotSwitch, //"circle",
          itemStyle: {
            normal: {
              color:
                item.color == null
                  ? item.attrObj && item.attrObj.avglineColor
                  : item.color,
            },
          },
          lineStyle: {
            width:
              item.attrObj && item.attrObj.avglineWidth
                ? item.attrObj.avglineWidth
                : 2,
            opacity: item.opacity,
          },
          data: item.hisSimulatePoints.map((itemsub) => {
            return [
              dayjs(itemsub.dataTime).format("YYYY-MM-DD HH:mm:ss"),
              itemsub.avgValue,
            ];
          }),
        }
      );
    });
    if (JSON.stringify(alarmList) != "{}") {
      xdataalarm = alarmList.allTimes.map((item) => {
        return dayjs(item).format("YYYY-MM-DD HH:mm:ss");
      });
      alarmList.hisAlarmLines.forEach((item) => {
        serArralarm.push({
          type: "line",
          step: "start",
          xAxisIndex: 1,
          smooth: false,
          symbol: "none",
          data: item.hisAlarmPoints.map((itemsub, index) => {
            return [
              dayjs(itemsub.dataTime).format("YYYY-MM-DD HH:mm:ss"),
              itemsub.value,
            ];
          }),
          itemStyle: {
            normal: {
              lineStyle: {
                color:
                  item.type == 0
                    ? "rgba(255, 153, 0, 1)"
                    : "rgba(103, 194, 58, 1)",
                type: "dashed",
              },
            },
          },
        });
      });
    }
    serArr = serArr.concat(serArralarm);
  }
  let option = {
    tooltip: {
      show:true,
      // trigger: "axis",
      formatter: function (param) {
        if (param.length > 0) {
          let arrNew = [];
          let arrName = _.uniq(
            param.map((item) => {
              return {
                name: item.seriesName,
                idx: item.dataIndex,
              };
            })
          );
          if (JSON.stringify(arr) != "{}") {
            arr.hisSimulateLines.forEach((item) => {
              arrName.forEach((itemsub) => {
                if (itemsub.name == item.pointId + item.place) {
                  arrNew.push({
                    place: item.place,
                    unit: item.unit,
                    ...item.hisSimulatePoints[itemsub.idx],
                  });
                }
              });
            });
          }
          let youBoxArr = _.onBy(arrNew, "pointId");
          state.youBoxList = [
            {
              place: "类型",
              maxValue: "最大值",
              minValue: "最小值",
              avgValue: "平均值",
              unit: undefined,
            },
          ].concat(youBoxArr);
          state.youBoxShow = true;
          state.youXY.x = param[0].dataIndex;
        }
      },
    },
    title: {
      text: props.attrObj && props.attrObj.chartTitle,
      left: "center",
      top: 10,
    },
    toolbox: {
      show: true,
      y: "-30",
    },
    brush: {
      xAxisIndex: "all",
      brushLink: "all",
      seriesIndex: "all",
      // 选框中的视觉元素样式
      inBrush: {
        symbol: "circle", // 图元图形 可以是'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin'
        symbolSize: 32, // 图元大小
        color: "red", // 图元颜色
        colorAlpha: 0.5, // 图元透明度
        opacity: 0.8, // 图元以及其附属物的透明度
      },
      // 未选中的视觉元素样式
      outOfBrush: {
        symbol: "circle", // 图元图形 可以是'circle', 'rect', 'roundRect', 'triangle', 'diamond', 'pin'
        symbolSize: 32, // 图元大小
        color: "red", // 图元颜色
        colorAlpha: 0.5, // 图元透明度
        opacity: 0.8, // 图元以及其附属物的透明度
      },
    },
    grid: {
      top: 50,
      left: 50,
      bottom: 30,
      right: 30,
    },
    xAxis: [
      {
        name: props.attrObj && props.attrObj.chartX,
        type: "category",
        boundaryGap: false,
        data: xdata,
        axisLine: {
          show: true,
          lineStyle: {
            color: "rgba(91, 109, 128, 0.8)",
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          show: true,
          color: "rgba(62, 70, 79, 1)",
        },
        splitLine: {
          show: props.attrObj && props.attrObj.chartGrid,
          lineStyle: {
            color: "rgba(91, 109, 128, 0.16)",
            type: "dashed",
          },
        },
        axisPointer: {
          show: false,
          lineStyle: {
            color: "#004E52",
            opacity: 0.5,
            width: 2,
            type: "solid",
          },
          snap: false, //true必须在点上，false任意位置
          handle: {
            show: true,
            size: 20,
            margin: 60,
            color: "#DC143C",
            throttle: 100,
            margin: -450,
            icon: `image://${imgIcon}`,
          },
          triggerTooltip: true,
          triggerEmphasis: true,
        },
      },
      {
        type: "category",
        boundaryGap: false,
        data: xdataalarm,
        axisLine: {
          show: false,
          lineStyle: {
            color: "rgba(91, 109, 128, 0.8)",
          },
        },
        axisTick: {
          show: false,
        },
        axisLabel: {
          show: false,
          color: "rgba(62, 70, 79, 1)",
        },
        splitLine: {
          show: false,
          lineStyle: {
            color: "rgba(91, 109, 128, 0.16)",
            type: "dashed",
          },
        },
      },
    ],
    yAxis: [
      {
        name: props.attrObj && props.attrObj.chartY,
        type: "value",
        splitNumber: 10, //纵向放大
        axisLine: {
          show: true,
          lineStyle: {
            color: "rgba(91, 109, 128, 0.8)",
          },
        },
        axisLabel: {
          formatter: "{value}",
          color: "rgba(62, 70, 79, 1)",
        },
        axisPointer: {
          show:false,
          value: 200,
          lineStyle: {
            color: "#004E52",
            opacity: 0.5,
            width: 2,
            type: "dashed",
          },
          label: {
            formatter: function (param) {
              state.youXY.y = param.value;
              return;
            },
          },
          snap: false,
          value: 100,
          handle: {
            show: true,
            size: 20,
            margin: 60,
            color: "#DC143C",
            throttle: 100,
          },
          triggerTooltip: false,
        },
        splitLine: {
          show: props.attrObj && props.attrObj.chartGrid,
          lineStyle: {
            color: "rgba(91, 109, 128, 0.16)",
            type: "dashed",
          },
        },
      },
    ],
    series: serArr,
  };
  chartCon.setOption(option, true);
  chartCon.on("click", function (param) {
    //拐点弹框位置及弹框数据
    if (param.event.offsetX > 1400) {
      param.event.offsetX = param.event.offsetX - 400;
    }
    state.xydata.x = param.event.offsetX;
    state.xydata.y = param.event.offsetY;
    state.symShow = true;
    if (JSON.stringify(arr) != "{}") {
      arr.hisSimulateLines.forEach((item) => {
        if (param.seriesName == item.pointId + item.place) {
          let dataObj = item.hisSimulatePoints[param.dataIndex];
          state.symbolObj = {
            pointId: item.pointId,
            pointName: item.sensorName,
            place: item.place,
            timeRange: [dataObj.intervalStart, dataObj.intervalEnd],
            list: [
              {
                label: "最大值",
                value: dataObj.maxValue,
                unit: item.unit,
                state: item.color == null ? "blue" : item.color,
              },
              {
                label: "最大值时刻",
                unit: dayjs(dataObj.maxValueTime).format("YYYY-MM-DD HH:mm:ss"),
              },
              {
                label: "最小值",
                value: dataObj.minValue,
                unit: item.unit,
                state: "blue",
              },
              {
                label: "平均值",
                value: dataObj.avgValue,
                unit: item.unit,
                state: "blue",
              },
              {
                label: "报警",
                value: dataObj.alarmNum,
                unit: item.unit,
                state: "blue",
              },
              {
                label: "累计时长",
                unit: dataObj.alarmDuration,
                state: "",
              },
              {
                label: "断电",
                value: dataObj.cutNum,
                unit: item.unit,
                state: "blue",
              },
              {
                label: "累计时长",
                unit: dataObj.cutDuration,
                state: "",
              },
              {
                label: "馈电异常",
                value: dataObj.feedNum,
                unit: item.unit,
                state: "blue",
              },
              {
                label: "累计时长",
                unit: dataObj.feedDuration,
                state: "",
              },
            ],
          };
        }
      });
    }
  });
  chartCon.dispatchAction({
    type: "none",
    key: "brush",
    removeOnClick: true,
    brushOption: {
      brushType: "clear", // 指定选框类型
    },
  });
  chartCon.on("brushEnd", function (params) {
    if (params.areas.length != 0) {
      let start = params.areas[0].coordRange[0];
      let end = params.areas[0].coordRange[1];
      if (xdata.length > 0) {
        let startTime = xdata[start];
        let endTime = xdata[end];
        emits("toolChange", {
          type: "dateType",
          data: [startTime, endTime],
          brushValue: "7",
        });
      }
    }
  });
}

// 关闭曲线抽屉
const closeChart = () => {
  emits("closeChart", false);
};

watch(() => open_chart.value, (val) => {
  if (val) {
    nextTick(() => {
      chartCon = echarts.init(document.getElementById("chart"));
      getChartData();
    });
  }
});
onMounted(() => {
});
</script>

<style lang="scss" scoped>
::v-deep .detail {
  width: 1200px !important;
  .d_header .title{
    display: flex;
    align-items: center;
  }
  .el-drawer__body {
    padding: 0;
  }
  .detail_box {
    padding: 16px;
    width: 100%;
    height: 600px;
    display: flex;
    justify-content: center;
    align-items: center;
    #chart{
      width: 100%;
      height: 100%;
    }
  }
}
</style>
